<template>
  <div class="out">
    <div class="topBack">
        <div class="storeName">

        </div>
        <van-swipe :autoplay="5000" indicator-color="white" lazy-render>
            <van-swipe-item v-for="(item, index) in bannerList" :index="item.bannerId">
                <img class="homeBack" :src="item.imageUrl" />
            </van-swipe-item>
        </van-swipe>
    </div>
    <div class="option">
        <div class="item" v-for="item in featureData" :key="item.typeId">
            <span class="title" :style="{'color': item.colorValue, 'border-color': item.colorValue}">{{ item.typeName}}</span>
            <div class="optionBtnArea">
                <div class="optionBtnItem app-button" 
                    v-for="data in item.featureList" 
                    :key="data.featureId" 
                    :class="{ 'fullscreen': activeFeatureId == data.featureId }"
                    @mousedown="handleMouseDown($event, data.featureId)"
                    @transitionend="handleTransitionEnd(data.featureUri)" 
                >
                    <img class="optionBtnItemIcon" :style="data.iconBuChongStyle == 'none'? '' : data.iconBuChongStyle" :src="data.iconPath">
                    <div v-if="activeFeatureId !== data.featureId" class="optionBtnItemText" :style="data.wenZiBuChongStyle == 'none'? '' : data.wenZiBuChongStyle">{{ data.featureName }}</div>
                </div>
                <div v-if="activeFeatureId" class="backcover"></div>
            </div>
        </div>
    </div>
    <van-floating-bubble v-if="allXiaoQuList.length > 1 && !userInfo.xiaoQuId" magnetic="x" :gap="10" axis="xy" v-model:offset="offset" @click="communityModelShow = true">
        <template #default>
            <!-- 带提示信息的浮窗 -->
            <!-- <van-popover v-model:show="showPopover" :actions="actions" theme="dark" placement="left" trigger="manual">
                <template #reference>
                    <div class="floatingContentOut">
                        <svg t="1743645736794" class="icon" viewBox="0 0 1058 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9296" width="28" height="28">
                            <path d="M653.175467 948.1216V315.255467h248.490666v630.510933h-248.490666v2.389333z m-529.3056 0V78.2336h444.893866v867.498667H123.869867v2.389333z m859.818666 0V236.919467h-330.513066V0H41.642667v945.7664h-40.96V1024h1024v-78.2336H983.722667v2.389333z m-593.988266-356.693333h99.328v117.316266h-99.328v-117.316266z m-181.4528 0h99.328v117.316266H208.213333v-117.316266z m526.882133 0h81.988267v117.316266h-81.988267v-117.316266z m0-195.6864h81.988267v117.316266h-81.988267v-117.316266z m-345.429333 0h99.328v117.316266h-99.328v-117.316266z m-181.4528 0h99.328v117.316266H208.213333v-117.316266zM389.700267 197.973333h99.328v117.316267h-99.328V197.9392z m-181.4528 0h99.328v117.316267H208.213333V197.9392z" fill="#ffffff" p-id="9297"></path>
                        </svg>
                    </div>
                </template>
            </van-popover> -->
            <div class="floatingContentOut">
                <svg t="1743645736794" class="icon" viewBox="0 0 1058 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9296" width="28" height="28">
                    <path d="M653.175467 948.1216V315.255467h248.490666v630.510933h-248.490666v2.389333z m-529.3056 0V78.2336h444.893866v867.498667H123.869867v2.389333z m859.818666 0V236.919467h-330.513066V0H41.642667v945.7664h-40.96V1024h1024v-78.2336H983.722667v2.389333z m-593.988266-356.693333h99.328v117.316266h-99.328v-117.316266z m-181.4528 0h99.328v117.316266H208.213333v-117.316266z m526.882133 0h81.988267v117.316266h-81.988267v-117.316266z m0-195.6864h81.988267v117.316266h-81.988267v-117.316266z m-345.429333 0h99.328v117.316266h-99.328v-117.316266z m-181.4528 0h99.328v117.316266H208.213333v-117.316266zM389.700267 197.973333h99.328v117.316267h-99.328V197.9392z m-181.4528 0h99.328v117.316267H208.213333V197.9392z" fill="#ffffff" p-id="9297"></path>
                </svg>
            </div>
        </template>
    </van-floating-bubble>
    <van-overlay :show="communityModelShow" z-index="1000">
        <div class="communitySelectOut">
            <div class="communitySelect">
                <div class="titleArea">
                    <div class="btn"></div>
                    <div class="titleContent">所有小区</div>
                    <div class="btn" @click="communityModelShow = false">取消</div>
                </div>
                <div class="communityList">
                    <van-radio-group v-model="tmpSelectedXiaoQuId">
                        <van-cell-group inset checked-color="#187eff">
                            <van-cell v-for="item in allXiaoQuList" :key="item.xiaoQuId" :title="item.xiaoQuName" clickable @click="tmpSelectedXiaoQuId = item.xiaoQuId">
                                <template #right-icon>
                                    <van-radio :name="item.xiaoQuId" />
                                </template>
                            </van-cell>
                        </van-cell-group>
                    </van-radio-group>
                </div>
                <van-button type="primary" color="#187eff" @click="changeCommunityHandler">确定</van-button>
            </div>
        </div>
    </van-overlay>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
import{ ref,onMounted } from 'vue'
import { noLoginFeature } from '@/api/feature/index.js'
import { postBannerList } from '@/api/banner/index.js'
import { postXiaoQuList } from '@/api/xiaoqu/index.js'
import { postStoreInfo } from '@/api/fangWuInfo/index.js'
import { pageConstant } from '@/config/contant.js'
import { store } from 'xijs';
import { getUserId } from '@/config/config.js'

const activeFeatureId = ref('')
const isTransitioning = ref(false)
const handleMouseDown = (event, featureId) => {
    // 只有在动画未进行时才触发
    if (!isTransitioning.value) {
        const button = event.currentTarget;
        const rect = button.getBoundingClientRect();

        // 1. 设置初始状态（与按钮原始位置和尺寸相同）
        button.style.position = 'fixed';
        button.style.top = `${rect.top}px`;
        button.style.left = `${rect.left}px`;
        button.style.width = `${rect.width}px`;
        button.style.height = `${rect.height}px`;

        // 2. 强制重绘（触发过渡）
        void button.offsetWidth;

        // 3. 切换到全屏状态
        isTransitioning.value = true
        activeFeatureId.value = featureId
        button.style.top = '0';
        button.style.left = '0';
        button.style.width = '100vw';
        button.style.height = '100vh';
    }
}
let lastExecutionTime = 0;
const handleTransitionEnd = (pathName) => {
    const now = Date.now();
    if (now - lastExecutionTime < 500) {
        return; // 如果距离上次执行不到500ms，直接返回
    }
    lastExecutionTime = now;

    if (pathName) {
        if (pathName === '/login') {
            store.remove(pageConstant.storageSyncUserKey)
            sessionStorage.removeItem('selectedXiaoQuId');

            router.push({
                path: pathName
            })
        } else {
            router.push({
                path: pathName
            })
        }
    }
}
/**
 * 判断是否登录并且获取首页按钮数据
 */
const featureData = ref([])
const noLoginFeatureHandler = () => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    });

    noLoginFeature({}).then(res => {
        // 关闭加载中提示
        closeToast();

        if (res.data.code == pageConstant.okCode) {
            featureData.value = res.data.data
        } else {
            showToast(res.data.msg);
        }
    })
    .catch((err) => {
        console.log(err)
    })
}

/**
 * 获取banner图数据
 */
const bannerList = ref([])
const loadHomeBackImageHandler = (xiaoQuId) => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    });

    postBannerList({
        xiaoQuId: xiaoQuId
    }).then(res => {
        // 关闭加载中提示
        closeToast();

        if (res.data.code == pageConstant.okCode) {
            bannerList.value = res.data.data
        } else {
            showToast(res.data.msg);
        }
    })
    .catch((err) => {
        console.log(err)
    })
}


/**
 * 首页浮窗功能, 342
 */
const offset = ref({ x: -58 , y: 500 })
// 带提示信息的浮窗
// const showPopover = ref(true);
// const actions = ref([{ text: '点此按钮可以切换小区' }])
const communityModelShow = ref(false)
const allXiaoQuList = ref([])
const tmpSelectedXiaoQuId = ref('')
const selectedXiaoQuId = ref('')
const userInfo = ref(JSON.parse(store.get(pageConstant.storageSyncUserKey).value))
const huxing=ref('');
const bianhao=ref('');
const xiaoqu=ref('');
const loadStoreInfoData=()=>{
    const userId=getUserId();
    if(userId){
        postStoreInfo({userId:userId}).then(res=>{
            if(res.data.code==pageConstant.okCode){
                if(res.data.data){
                    // console.log(res.data.data);
                    const storeInfo=res.data.data;
                    huxing.value=storeInfo.huXing;
                    bianhao.value=storeInfo.bianHao;
                }
            }
        }).catch(err=>{
            console.log(err)
        })
    }


}
const loadAllXiaoQuListHandler = () => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    });

    postXiaoQuList({}).then(res => {
        // 关闭加载中提示
        closeToast();

        if (res.data.code == pageConstant.okCode) {
            allXiaoQuList.value = res.data.data
            if (allXiaoQuList.value.length == 0) {
                showDialog({
                    message: '暂无小区数据，请先配置小区',
                })
                return
            }

            if (sessionStorage.getItem("selectedXiaoQuId") && sessionStorage.getItem("selectedXiaoQuId").length > 0) {
                tmpSelectedXiaoQuId.value = sessionStorage.getItem("selectedXiaoQuId")
                selectedXiaoQuId.value = sessionStorage.getItem("selectedXiaoQuId")
            } else {
                tmpSelectedXiaoQuId.value = allXiaoQuList.value[0].xiaoQuId
                selectedXiaoQuId.value = allXiaoQuList.value[0].xiaoQuId
                sessionStorage.setItem("selectedXiaoQuId", allXiaoQuList.value[0].xiaoQuId);
            }

            // 加载小区对应的banner
            let xiaoQuId = sessionStorage.getItem("selectedXiaoQuId")

            loadHomeBackImageHandler(xiaoQuId)
        } else {
            showToast(res.data.msg);
        }
    })
    .catch((err) => {
        console.log(err)
    })
}
if (store.get(pageConstant.storageSyncUserKey).status == 0) {
    featureData.value = userInfo.value.featureVOList

    if (userInfo.value.xiaoQuId && userInfo.value.xiaoQuId.length > 0) {
        if (sessionStorage.getItem("selectedXiaoQuId") && sessionStorage.getItem("selectedXiaoQuId").length > 0) {
            tmpSelectedXiaoQuId.value = sessionStorage.getItem("selectedXiaoQuId")
            selectedXiaoQuId.value = sessionStorage.getItem("selectedXiaoQuId")
        } else {
            tmpSelectedXiaoQuId.value = userInfo.value.xiaoQuId
            selectedXiaoQuId.value = userInfo.value.xiaoQuId
            sessionStorage.setItem("selectedXiaoQuId", userInfo.value.xiaoQuId);
        }
        loadHomeBackImageHandler(userInfo.value.xiaoQuId)
    } else {
        loadAllXiaoQuListHandler()
    }
} else {
    noLoginFeatureHandler()
    loadAllXiaoQuListHandler()
}
const changeCommunityHandler = () => {
    selectedXiaoQuId.value = tmpSelectedXiaoQuId.value
    communityModelShow.value = false
    sessionStorage.setItem("selectedXiaoQuId", tmpSelectedXiaoQuId.value)

    loadHomeBackImageHandler(selectedXiaoQuId.value)
}

onMounted(()=>{
    loadStoreInfoData();
})
</script>

<style lang="scss" scoped>
.out {
    background-color: rgb(241, 241, 241);
    min-height: 100dvh;

    .topBack {
        position: relative;
        .bannertitle {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 10;
            color: #fff;
            font-size: 30px;
            font-weight: bolder;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        .homeBack {
            width: 100%;
        }
        .logoImage {
            position: absolute;
            top: 2px;
            left: 5px;
        }
        .titleImage {
            position: absolute;
            top: -3px;
            left: 30px;
        }
        .title {
            font-weight: 1000;
            position: absolute;
            top: 2px;
            left: 40px;
            color: #fff;
        }
    }

    .option {
        padding: 10px 18px 20px 18px;
        .item {
            margin-top: 20px;

            .title {
                margin-left: 3px;
                font-weight: bolder;
                padding-bottom: 5px;
                border-bottom: 2px solid #fff;
            }

            .optionBtnArea {
                display: flex;
                flex-flow: row wrap;
                margin-top: 15px;
                gap: 10px;

                .optionBtnItem {
                    height: 83px;
                    width: 83px;
                    background-color: #fff;
                    border-radius: 10px;
                    box-shadow: 0 1px 8px rgba(0, 0, 0, 0.3);
                    display: flex;
                    flex-flow: column nowrap;
                    align-items: center;

                    .optionBtnItemIcon {
                        margin-top: 17px;
                    }
                    .optionBtnItemText {
                        margin-top: 7px;
                        font-weight: bolder;
                        color: #344054;
                        font-size: 15px;
                    }
                }

                .app-button {
                    transition: all 0.5s ease;
                    position: relative;
                }
                .fullscreen {
                    position: fixed;
                    // top: 0;
                    // left: 0;
                    // width: 100vw;
                    // height: 100vh;
                    border-radius: 20px;
                    z-index: 1000;
                    background-color: #FFF;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    /* 全屏状态 */
                    transform: scale(1) translate(0, 0); /* 放大倍数根据需要调整 */
                }
                .backcover {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100vw;
                    height: 100vh;
                    background-color: rgb(102, 104, 104);
                    opacity: 0.5;
                    z-index: 999;
                }
            }
        }

        
        .first {
            color: #46d776;
            .title {
                border-bottom-color: rgb(70, 215, 118);
            }
        }
        .second {
            color: #187eff;
            .title {
                border-color: rgb(24, 126, 255);
            }
        }
        .third {
            color: #efb979;
            .title {
                border-color: rgb(239, 185, 121);
            }
        }
        .forth {
            color: #ef79ea;
            .title {
                border-color: #ef79ea;
            }
        }
    }

    .communitySelectOut {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .communitySelect {
            width: 320px;
            // height: 500px;
            background-color: #fff;
            border-radius: 10px;
            padding: 0 10px 0 18px;
            box-sizing: border-box;

            .titleArea {
                display: flex;
                flex-flow: row nowrap;
                align-items: center;
                justify-content: space-between;
                padding: 18px 8px 18px 0;
            }

            .titleContent {
                font-size: 18px;
            }

            .btn {
                font-size: 15px;
                width: 30px;
                text-align: right;
                color: #187eff;
            }
        }

        .communityList {
            height: 300px;
            overflow: auto;

            ::v-deep .van-cell-group--inset {
                margin: 0;

                .van-cell--clickable {
                    padding-left: 0;
                    padding-right: 8px;
                }

                .van-cell:after {
                    right: 8px;
                    left: 0;
                }
            }
        }
        ::v-deep .van-button {
            width: 70%;
            font-size: 16px;
            height: 38px;
            margin: 10px 15%;
        }
    }
}
.floatingContentOut {
    display: flex;
    flex-flow: column wrap;
    justify-content: center;
    align-items: center;
    width: 48px;
    height: 48px;
    font-size: 15px;
}
</style>